package it.unibo.mumu.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import android.app.Dialog;
import android.content.Context;
//import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;


public class Downloader{
	
	ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    TextView cur_val;
    private String error;

	public Downloader(Context context) {
		this.error = null;
	}


	public void downloadResourceAndUnzip(String address, String nameFile, String path){
		try {
    		// Code block for determining HTTP or https
            HttpURLConnection conn = null;
            URL url = new URL(address);
            if (url.getProtocol().toLowerCase().equals("https")) {
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            conn.connect();
            
          //set the path where we want to save the file          
            File internalPath = new File(path);
            //create a new file, to save the downloaded file
            File file = new File(internalPath,nameFile);
            if(file.exists()){
            	file.delete();
            }
            FileOutputStream fileOutput = new FileOutputStream(file);
 
            InputStream inputStream = conn.getInputStream();
 
            totalSize = conn.getContentLength();
            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
 
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
            }
            //close the output stream when complete //
            fileOutput.close();            
            doUnzip(nameFile, path);
   
            deleteFile(path+"/"+nameFile);
    	} catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);       
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);         
            e.printStackTrace();
        }
        catch (final Exception e) {
            showError("Error : Please check your internet connection");
        }  
	}
	
	
	public void downloadResource(String address, String nameFile, String path){
		try {
    		// Code block for determining HTTP or https
            HttpURLConnection conn = null;
            URL url = new URL(address);
            if (url.getProtocol().toLowerCase().equals("https")) {
                trustAllHosts();
                HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            conn.connect();
            
          //set the path where we want to save the file          
            File internalPath = new File(path);//getFilesDir();
//            Log.i("DIR1", internalPath.toString());
//            Log.i("DIR2", "PATH: " + path);
            //create a new file, to save the downloaded file
            File file = new File(internalPath,nameFile);
            if(file.exists()){
            	file.delete();
            }
            FileOutputStream fileOutput = new FileOutputStream(file);
 
            InputStream inputStream = conn.getInputStream();
 
            totalSize = conn.getContentLength();
            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0;
 
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
            }
            //close the output stream when complete //
            fileOutput.close();            
    	} catch (final MalformedURLException e) {
            showError("Error : MalformedURLException " + e);       
            e.printStackTrace();
        } catch (final IOException e) {
            showError("Error : IOException " + e);         
            e.printStackTrace();
        }
        catch (final Exception e) {
            showError("Error : Please check your internet connection");
        }  
	}
	
	
	final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
 };


  /**
   * Trust every server - dont check for any certificate
   */
  private static void trustAllHosts() {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[] {};
                    }

					@Override
					public void checkClientTrusted(X509Certificate[] arg0,
							String arg1) throws CertificateException {
					}

					@Override
					public void checkServerTrusted(X509Certificate[] arg0,
							String arg1) throws CertificateException {
					}
            } };

            // Install the all-trusting trust manager
            try {
                    SSLContext sc = SSLContext.getInstance("TLS");
                    sc.init(null, trustAllCerts, new java.security.SecureRandom());
                    HttpsURLConnection
                                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
            } catch (Exception e) {
                    e.printStackTrace();
            }
    }
  
  
//------ unzip file -----
  public void doUnzip(String nameFile, String path) {
  	String zipFile = path + "/" +nameFile; 
      String unzipLocation = path+"/"; 
//       Log.i("MYAPP path", unzipLocation);
      Decompress dec = new Decompress(zipFile, unzipLocation); 
      dec.unzip(); 
	}
  
  void showError(final String err){
//      runOnUiThread(new Runnable() {
//          public void run() {
//              Toast.makeText(Downloader.this, err, Toast.LENGTH_LONG).show();
//          }
//      });
	  error = err;
	  
  }
  
  
  private void deleteFile(String name){
	  try{
		  
  		File file = new File(name);

  		if(file.delete()){
  			System.out.println(file.getName() + " is deleted!");
  		}else{
  			System.out.println("Delete operation is failed.");
  		}

  	}catch(Exception e){

  		e.printStackTrace();

  	}
  }


public String getError() {
	return error;
}
	
}

